package cmd

import (
	"database/sql"
	"fmt"
	"gitee.com/cdsailyj/go-vpn/common/tool"
	"gitee.com/cdsailyj/go-vpn/common/util"
	"gitee.com/cdsailyj/go-vpn/initialize"
	"regexp"
	"strings"
	"unicode"
)

type AptCmd struct{}

type Aptitude struct {
	ID               string `db:"ID" json:"ID" form:"ID"`
	USER_ID          string `db:"USER_ID" json:"USER_ID" form:"USER_ID"`
	USER_OFFICE_ID   string `db:"USER_OFFICE_ID" json:"USER_OFFICE_ID" form:"USER_OFFICE_ID"`
	USER_OFFICE_NAME string `db:"USER_OFFICE_NAME" json:"USER_OFFICE_NAME" form:"USER_OFFICE_NAME"`
}

type SysUser struct {
	ID              string `db:"ID" json:"ID" form:"ID"`
	ENTERPRISE_ID   string `db:"ENTERPRISE_ID" json:"ENTERPRISE_ID" form:"ENTERPRISE_ID"`
	ENTERPRISE_NAME string `db:"ENTERPRISE_NAME" json:"ENTERPRISE_NAME" form:"ENTERPRISE_NAME"`
}

type HealthData struct {
	DEPART_NAME        sql.NullString `db:"DEPART_NAME" json:"DEPART_NAME" form:"DEPART_NAME"`
	PROJECT_NAME       sql.NullString `db:"PROJECT_NAME" json:"PROJECT_NAME" form:"PROJECT_NAME"`
	RESULT_VALUE       sql.NullString `db:"RESULT_VALUE" json:"RESULT_VALUE" form:"RESULT_VALUE"`
	UNIT               sql.NullString `db:"UNIT" json:"UNIT" form:"UNIT"`
	REFERENCE_VALUE    sql.NullString `db:"REFERENCE_VALUE" json:"REFERENCE_VALUE" form:"REFERENCE_VALUE"`
	ABNORMAL           sql.NullString `db:"ABNORMAL" json:"ABNORMAL" form:"ABNORMAL"`
	SUMMARY            sql.NullString `db:"SUMMARY" json:"SUMMARY" form:"SUMMARY"`
	SUMMARY_DATE       sql.NullString `db:"SUMMARY_DATE" json:"SUMMARY_DATE" form:"SUMMARY_DATE"`
	SUMMARY_DOCTOR     sql.NullString `db:"SUMMARY_DOCTOR" json:"SUMMARY_DOCTOR" form:"SUMMARY_DOCTOR"`
	ID_CARD            sql.NullString `db:"ID_CARD" json:"ID_CARD" form:"ID_CARD"`
	NAME               sql.NullString `db:"NAME" json:"NAME" form:"NAME"`
	CHECK_DATE         sql.NullString `db:"CHECK_DATE" json:"CHECK_DATE" form:"CHECK_DATE"`
	HOSPITAL_NAME      sql.NullString `db:"HOSPITAL_NAME" json:"HOSPITAL_NAME" form:"HOSPITAL_NAME"`
	CHECK_DOCTOR       sql.NullString `db:"CHECK_DOCTOR" json:"CHECK_DOCTOR" form:"CHECK_DOCTOR"`
	CHECK_RESULT       sql.NullString `db:"CHECK_RESULT" json:"CHECK_RESULT" form:"CHECK_RESULT"`
	CHECK_SUGGESTION   sql.NullString `db:"CHECK_SUGGESTION" json:"CHECK_SUGGESTION" form:"CHECK_SUGGESTION"`
	SECOND_OFFICE_ID   sql.NullString `db:"SECOND_OFFICE_ID" json:"SECOND_OFFICE_ID" form:"SECOND_OFFICE_ID"`
	SECOND_OFFICE_NAME string         `db:"SECOND_OFFICE_NAME" json:"SECOND_OFFICE_NAME" form:"SECOND_OFFICE_NAME"`
	THIRD_OFFICE_ID    sql.NullString `db:"THIRD_OFFICE_ID" json:"THIRD_OFFICE_ID" form:"THIRD_OFFICE_ID"`
	THIRD_OFFICE_NAME  string         `db:"THIRD_OFFICE_NAME" json:"THIRD_OFFICE_NAME" form:"THIRD_OFFICE_NAME"`
}

type HealthOffice struct {
	ID                 string         `db:"ID" json:"ID" form:"ID"`
	SECOND_OFFICE_ID   sql.NullString `db:"SECOND_OFFICE_ID" json:"SECOND_OFFICE_ID" form:"SECOND_OFFICE_ID"`
	SECOND_OFFICE_NAME sql.NullString `db:"SECOND_OFFICE_NAME" json:"SECOND_OFFICE_NAME" form:"SECOND_OFFICE_NAME"`
	THIRD_OFFICE_ID    sql.NullString `db:"THIRD_OFFICE_ID" json:"THIRD_OFFICE_ID" form:"THIRD_OFFICE_ID"`
	THIRD_OFFICE_NAME  sql.NullString `db:"THIRD_OFFICE_NAME" json:"THIRD_OFFICE_NAME" form:"THIRD_OFFICE_NAME"`
	WORK_UNIT_ID       sql.NullString `db:"WORK_UNIT_ID" json:"WORK_UNIT_ID" form:"WORK_UNIT_ID"`
	PARENT_WORK_IDS    sql.NullString `db:"PARENT_WORK_IDS" json:"PARENT_WORK_IDS" form:"PARENT_WORK_IDS"`
}

type EmpBasicInfo struct {
	ID              string         `db:"ID" json:"ID" form:"ID"`
	ID_NO           sql.NullString `db:"ID_NO" json:"ID_NO" form:"ID_NO"`
	WORK_UNIT_ID    sql.NullString `db:"WORK_UNIT_ID" json:"WORK_UNIT_ID" form:"WORK_UNIT_ID"`
	PARENT_WORK_IDS sql.NullString `db:"PARENT_WORK_IDS" json:"PARENT_WORK_IDS" form:"PARENT_WORK_IDS"`
}

type EmpWeightClock struct {
	EMP_ID        sql.NullString  `db:"EMP_ID" json:"EMP_ID" form:"EMP_ID"`
	CLOCKING_TIME sql.NullString  `db:"CLOCKING_TIME" json:"CLOCKING_TIME" form:"CLOCKING_TIME"`
	BMI           sql.NullString  `db:"BMI" json:"BMI" form:"BMI"`
	CREATE_DATE   *util.LocalTime `db:"CREATE_DATE" json:"CREATE_DATE" form:"CREATE_DATE"`
}

func (t *AptCmd) Clock() {
	db, _ := initialize.GetYwkDB()
	var results []EmpWeightClock
	sqlString := fmt.Sprintf(`SELECT 
      EMP_ID,
      BMI,
      CREATE_DATE,
      CLOCKING_TIME
  FROM (
      SELECT CLOCKING_TIME, CREATE_DATE, EMP_ID, BMI, ROW_NUMBER() OVER (PARTITION BY EMP_ID ORDER BY CREATE_DATE DESC) as rn
      FROM EMP_WEIGHT_CLOCKING
      WHERE DEL_FLAG = 0 AND CLOCKING_TIME is not null AND BMI > 0 AND BMI < 999
  )
WHERE rn = 1`)
	db.Select(&results, sqlString)
	fmt.Printf("总数：%#v \n", len(results))

	success := 1
	for _, v := range results {

		if !v.EMP_ID.Valid {
			return
		}

		_, err := db.Exec("UPDATE EMP_FAT set BMI_NEW = :1 , BMI_NEW_DATE = TO_DATE(:2, 'yyyy-mm-dd HH24:mi:ss')  WHERE EMP_ID = :3", v.BMI, fmt.Sprintf("%s 00:00:00", v.CLOCKING_TIME.String), v.EMP_ID)
		if err != nil {
			fmt.Printf("修改失败：%#v \n", err)
			return
		}
		fmt.Printf("修改成功：%#v \t  %#v\n", v, success)
		success++
	}

}

func (t *AptCmd) Office() {
	db, _ := initialize.GetYwkDB()
	myFunc := func(a any) {
		v, _ := a.(HealthOffice)

		if !v.WORK_UNIT_ID.Valid {
			return
		}
		parents := officeServiceApp.GetOfficeLevelName(v.WORK_UNIT_ID.String)
		if true {
			fmt.Println(v.WORK_UNIT_ID.String, parents)
			return
		}

		if !v.SECOND_OFFICE_NAME.Valid && len(parents) > 0 {
			thirdName := tool.If(len(parents) > 1, parents[1].NAME.String, "")
			ret, err := db.Exec("UPDATE EMP_HEALTH_CHECK_NEW set SECOND_OFFICE_NAME = :1 , THIRD_OFFICE_NAME = :2  WHERE ID = :3", parents[0], thirdName, v.ID)
			if err != nil {
				fmt.Printf("修改失败：%#v \n", err)
				return
			}
			fmt.Printf("修改成功：%#v ====>  %#v\n", v, ret)
		}
	}

	task := &util.AsyncTask{ChanLen: 55000, TaskNum: 1}
	task.Start(myFunc)

	n := 0
	limit := 500
	for i := 0; ; i++ {
		var results []HealthOffice
		sqlString := fmt.Sprintf(` SELECT a.ID, a.SECOND_OFFICE_ID, a.SECOND_OFFICE_NAME, a.THIRD_OFFICE_ID, a.THIRD_OFFICE_NAME, b.WORK_UNIT_ID, b.PARENT_WORK_IDS
 FROM  EMP_HEALTH_CHECK_NEW a left join EMP_BASIC_INFO b ON a.ID_CARD = b.ID_NO 
 ORDER BY  a.CREATE_DATE  ASC OFFSET :1  ROWS FETCH NEXT :2 ROWS ONLY `)
		err := db.Select(&results, sqlString, i*limit, limit)
		if err != nil {
			fmt.Printf("错误：%#v \n", err)
			return
		}
		if results == nil {
			break
		}

		for _, v := range results {
			n++
			task.Chan <- v
			fmt.Printf("数量：%#v \n", n)
		}
	}

	task.Stop()
}

func (t *AptCmd) Export() {
	db, _ := initialize.GetYwkDB()
	limit := 1000000

	year := 2025
	officeMap, _ := officeServiceApp.GetOfficeMap()

	for i := 1; i < 2; i++ {
		var results []HealthData
		//month := tool.If(i > 9, fmt.Sprintf("%d", i), fmt.Sprintf("0%d", i))
		monthEnd := tool.If(i+1 > 9, fmt.Sprintf("%d", i+1), fmt.Sprintf("0%d", i+1))
		if monthEnd == "13" {
			monthEnd = "01"
			year += 1
		}
		start := "2025-01-01"
		end := "2025-11-01"

		sqlString := `SELECT
  a.DEPART_NAME,
  a.PROJECT_NAME,
  a.RESULT_VALUE,
  a.UNIT,
  a.REFERENCE_VALUE,
  a.ABNORMAL,
  
  b.SUMMARY,
  b.SUMMARY_DATE,
  b.SUMMARY_DOCTOR,
  
  c.ID_CARD,
  c.NAME,
  c.CHECK_DATE,
  c.HOSPITAL_NAME,
  c.CHECK_DOCTOR,
  c.CHECK_RESULT,
  c.CHECK_SUGGESTION,
  c.SECOND_OFFICE_ID,
  c.THIRD_OFFICE_ID 
FROM
  HEALTH_CHECK_PROJECT a
  LEFT JOIN HEALTH_CHECK_DEPART b ON a.CHECK_ID = b.CHECK_ID 
  AND a.DEPART_NO = b.DEPART_NO
  LEFT JOIN EMP_HEALTH_CHECK_NEW c ON a.CHECK_ID = c.CHECK_ID 
WHERE
  c.DEL_FLAG = '0'  AND c.ID_CARD IN('413026198704076011', '650203198311130046', '650202199406290016', '650106198406180816')
  AND a.DEL_FLAG = '0' 
  AND b.DEL_FLAG = '0'
  AND c.CHECK_DATE BETWEEN :1 AND :2
  ORDER BY c.CHECK_DATE ASC 
  OFFSET 0 ROWS FETCH NEXT :3 rows ONLY`

		err := db.Select(&results, sqlString, start, end, limit)
		if err != nil {
			fmt.Printf("错误：%#v \n", err)
			return
		}
		if results == nil {
			break
		}

		for k, v := range results {

			if o2, ok := officeMap[v.SECOND_OFFICE_ID.String]; ok {
				results[k].SECOND_OFFICE_NAME = o2
			}
			if o3, ok := officeMap[v.THIRD_OFFICE_ID.String]; ok {
				results[k].THIRD_OFFICE_NAME = o3
			}
		}

		headers := []tool.ExcelSheetHeader{
			{Key: "DEPART_NAME", Label: "科室"},
			{Key: "PROJECT_NAME", Label: "项目"},
			{Key: "RESULT_VALUE", Label: "结果值"},
			{Key: "UNIT", Label: "单位"},
			{Key: "REFERENCE_VALUE", Label: "参考值"},
			{Key: "ABNORMAL", Label: "是否异常"},
			{Key: "SUMMARY", Label: "小结"},
			{Key: "SUMMARY_DATE", Label: "小结日期"},
			{Key: "SUMMARY_DOCTOR", Label: "小结医生"},
			{Key: "ID_CARD", Label: "身份证"},
			{Key: "NAME", Label: "姓名"},
			{Key: "CHECK_DATE", Label: "体检日期"},
			{Key: "HOSPITAL_NAME", Label: "医院"},
			{Key: "CHECK_DOCTOR", Label: "体检医生"},
			{Key: "CHECK_RESULT", Label: "体检结果"},
			{Key: "CHECK_SUGGESTION", Label: "体检建议"},
			{Key: "SECOND_OFFICE_NAME", Label: "二级单位"},
			{Key: "THIRD_OFFICE_NAME", Label: "三级单位"},
		}

		var allData []tool.ExcelCol[HealthData]
		for _, v := range results {
			allData = append(allData, tool.ExcelCol[HealthData]{Value: v})
		}
		sheet := []tool.ExcelSheet[HealthData]{
			{Name: "名单", Headers: headers, Data: allData},
		}
		excel, _ := tool.ExportExcel(sheet)

		err = excel.SaveAs(fmt.Sprintf("D:\\download\\%s.xlsx", start))
		if err != nil {
			fmt.Printf("输出结果: %#v \n", err)
		}
	}
}

func (t *AptCmd) Fix() {
	db, _ := initialize.GetYwkDB()
	dbXtk, _ := initialize.GetXtkDB()

	myFunc := func(a any) {
		v, _ := a.(Aptitude)
		var user SysUser
		sqlString2 := fmt.Sprintf(` SELECT ID, ENTERPRISE_ID, ENTERPRISE_NAME  FROM  SYS_USER WHERE  DEL_FLAG = '0' AND ID = :1 OFFSET 0  ROWS FETCH NEXT 1 ROWS ONLY `)
		err := dbXtk.Get(&user, sqlString2, v.USER_ID)
		if err != nil {
			fmt.Printf("账号查询错误：%#v \t %#v \n", v.USER_ID, err)
			return
		}
		//fmt.Printf("user：%#v \n", user)

		if user.ENTERPRISE_ID != v.USER_OFFICE_ID {
			ret, err := db.Exec("update SYS_USER_APTITUDE set USER_OFFICE_ID = :1 , USER_OFFICE_NAME = :2  WHERE USER_ID = :3", user.ENTERPRISE_ID, user.ENTERPRISE_NAME, user.ID)
			if err != nil {
				fmt.Printf("修改失败：%#v \n", err)
				return
			}
			fmt.Printf("修改成功：%#v ====> %#v ====>  %#v\n", v, user, ret)
		}
	}

	task := &util.AsyncTask{ChanLen: 55000, TaskNum: 500}
	task.Start(myFunc)

	n := 0
	for i := 0; ; i++ {
		var results []Aptitude

		sqlString := fmt.Sprintf(` SELECT ID, USER_ID, USER_OFFICE_ID, USER_OFFICE_NAME  FROM  SYS_USER_APTITUDE WHERE  DEL_FLAG = '0' ORDER BY  CREATE_DATE  ASC OFFSET :1  ROWS FETCH NEXT 50000 ROWS ONLY `)

		err := db.Select(&results, sqlString, i*50000)
		if err != nil {
			fmt.Printf("错误：%#v \n", err)
			return
		}
		if results == nil {
			break
		}
		//fmt.Printf("results：%#v \n", results)

		for _, v := range results {
			n++
			task.Chan <- v
			fmt.Printf("数量：%#v \n", n)
		}
	}

	task.Stop()

}

type Filing struct {
	ID                  string         `db:"ID" json:"ID" form:"ID"`
	APPROVAL_USER_ID    sql.NullString `db:"APPROVAL_USER_ID" json:"APPROVAL_USER_ID" form:"APPROVAL_USER_ID"`
	BUSINESS_DEPARTMENT sql.NullString `db:"BUSINESS_DEPARTMENT" json:"BUSINESS_DEPARTMENT" form:"BUSINESS_DEPARTMENT"`
}

type HealthCheckNew struct {
	ID               string         `db:"ID" json:"ID" form:"ID"`
	ID_CARD          sql.NullString `db:"ID_CARD" json:"ID_CARD" form:"ID_CARD"`
	CHECK_ID         sql.NullString `db:"CHECK_ID" json:"CHECK_ID" form:"CHECK_ID"`
	CHECK_RESULT     sql.NullString `db:"CHECK_RESULT" json:"CHECK_RESULT" form:"CHECK_RESULT"`
	CHECK_SUGGESTION sql.NullString `db:"CHECK_SUGGESTION" json:"CHECK_SUGGESTION" form:"CHECK_SUGGESTION"`
}

func (t *AptCmd) Sm4() {
	db, _ := initialize.GetYwkDB()

	myFunc := func(a any) {
		v, _ := a.(HealthCheckNew)
		idCard, err := t.Decrypt(v.ID_CARD.String)
		if err != nil {
			fmt.Printf("解密失败：%#v \t %#v \n", v.ID, err)
			return
		}

		CheckResult, err := t.Decrypt(v.CHECK_RESULT.String)
		if err != nil {
			db.Exec(`UPDATE EMP_HEALTH_CHECK_NEW SET  ID_CARD = :1  WHERE ID = :2`, idCard, v.ID)
			fmt.Printf("解密失败2：%#v \t %#v \n", v.ID, err)
			return
		}

		CheckSuggestion, err := t.Decrypt(v.CHECK_SUGGESTION.String)
		if err != nil {
			db.Exec(`UPDATE EMP_HEALTH_CHECK_NEW SET  ID_CARD = :1, CHECK_RESULT = :2  WHERE ID = :3`, idCard, CheckResult, v.ID)
			fmt.Printf("解密失败3：%#v \t %#v \n", v.ID, err)
			return
		}

		updateSQL := fmt.Sprintf(`UPDATE EMP_HEALTH_CHECK_NEW SET  ID_CARD = :1, CHECK_RESULT = :2, CHECK_SUGGESTION = :3  WHERE ID = :4`)
		ret, err := db.Exec(updateSQL, idCard, CheckResult, CheckSuggestion, v.ID)
		if err != nil {
			fmt.Printf("修改失败：%#v \t %#v \t %#v \n", v.ID, idCard, err)
			return
		}
		rows, _ := ret.RowsAffected()
		fmt.Printf("修改成功：%#v \t %#v\n", v.ID, rows)
	}

	task := &util.AsyncTask{ChanLen: 5000, TaskNum: 30}
	task.Start(myFunc)

	n := 0
	for i := 0; ; i++ {
		var results []HealthCheckNew

		sqlString := fmt.Sprintf(`SELECT ID, ID_CARD, CHECK_RESULT, CHECK_SUGGESTION  FROM  EMP_HEALTH_CHECK_NEW WHERE ID_CARD LIKE :1 ORDER BY  CREATE_DATE  ASC OFFSET :2  ROWS FETCH NEXT 1000 ROWS ONLY`)

		err := db.Select(&results, sqlString, "%=%", 0)
		if err != nil {
			fmt.Printf("查询列表错误：%#v \t %#v \n", sqlString, err)
			break
		}
		if results == nil {
			break
		}

		for _, v := range results {
			n++
			task.Chan <- v
		}
	}

	task.Stop()
}

type HealthCheckDepart struct {
	ID       string         `db:"ID" json:"ID" form:"ID"`
	SUMMARY  sql.NullString `db:"SUMMARY" json:"SUMMARY" form:"SUMMARY"`
	CHECK_ID sql.NullString `db:"CHECK_ID" json:"CHECK_ID" form:"CHECK_ID"`
}

// SanitizeText 移除特殊无效字符
func SanitizeText(text string) string {
	// 替换特殊空白字符
	text = strings.ReplaceAll(text, "\u00a0", "")
	text = strings.ReplaceAll(text, "\u2029", "") // 或直接移除

	// 创建特殊汉字映射表
	specialHanzi := map[rune]rune{
		'⻅': '见', // U+2E8D → U+89C1
		'⽌': '止', // U+2F5C → U+6B62
		'⾎': '血', // U+2F8E → U+8840
		'⾻': '骨', // U+2FBB → U+9AA8
		'⾯': '面', // U+2FAF → U+9762
		'⾐': '衣', // U+2F90 → U+8863
		'⾛': '走', // U+2F9B → U+8D70
		'⾚': '赤', // U+2F9A → U+8D64
		'⾼': '高', // U+2FBC → U+9AD8
		'⾁': '肉', // U+2F81 → U+8089 (肉)
		'⼒': '力', // U+2F4F → U+529B (力)
		'⼩': '小', // U+2F69 → U+5C0F (小)
		'⽬': '目', // U+2F6C → U+76EE (目)
		'⽪': '皮', // U+2F6A → U+76AE (皮)
		'⽓': '气', // U+2F53 → U+6C14 (气)
	}

	// 替换特殊汉字
	text = strings.Map(func(r rune) rune {
		if replacement, ok := specialHanzi[r]; ok {
			return replacement
		}
		return r
	}, text)

	// 移除非打印字符
	text = strings.Map(func(r rune) rune {
		if unicode.IsPrint(r) || unicode.IsSpace(r) {
			return r
		}
		return -1
	}, text)

	// 移除其他特殊字符（根据实际情况调整）
	re := regexp.MustCompile(`[^\p{Han}\p{L}\p{N}\s,.?!;:()-]`)
	return re.ReplaceAllString(text, "")
}

func (t *AptCmd) Depart() {
	db, _ := initialize.GetYwkDB()

	myFunc := func(a any) {
		v, _ := a.(HealthCheckDepart)
		summary, err := t.Decrypt(v.SUMMARY.String)
		if err != nil {
			db.Exec(`UPDATE HEALTH_CHECK_DEPART SET CHECK_NO = :1 WHERE ID = :2`, "1", v.ID)
			fmt.Printf("解密失败：%#v \t %#v \n", v.ID, err)
			return
		}

		updateSQL := fmt.Sprintf(`UPDATE HEALTH_CHECK_DEPART SET  SUMMARY = :1, CHECK_NO = :2 WHERE ID = :3`)
		//updateSQL := fmt.Sprintf(`UPDATE HEALTH_CHECK_DEPART SET  SUMMARY = :1 WHERE ID = :2`)
		ret, err := db.Exec(updateSQL, SanitizeText(summary), "1", v.ID)
		if err != nil {
			fmt.Printf("修改失败：%#v \t %#v \n", SanitizeText(summary), err)
			return
		}
		rows, _ := ret.RowsAffected()
		fmt.Printf("修改成功：%#v \t %#v\n", v.ID, rows)
	}

	task := &util.AsyncTask{ChanLen: 250000, TaskNum: 200}
	task.Start(myFunc)

	// 1955175869119225858
	for i := 0; ; i++ {
		var results []HealthCheckDepart

		sqlString := fmt.Sprintf(`SELECT ID, SUMMARY  FROM  HEALTH_CHECK_DEPART WHERE (CHECK_NO = '2' OR CHECK_NO is null)  OFFSET :1  ROWS FETCH NEXT 100000 ROWS ONLY`)

		err := db.Select(&results, sqlString, 0)
		if err != nil {
			fmt.Printf("查询列表错误：%#v \t %#v \n", sqlString, err)
			break
		}
		if results == nil {
			fmt.Printf("查询列表为空：%#v \t %#v \n", sqlString, err)
			break
		}

		for _, v := range results {
			task.Chan <- v
		}
	}

	task.Stop()
}

type HealthCheckProject struct {
	ID           string         `db:"ID" json:"ID" form:"ID"`
	CHECK_ID     sql.NullString `db:"CHECK_ID" json:"CHECK_ID" form:"CHECK_ID"`
	RESULT_VALUE sql.NullString `db:"RESULT_VALUE" json:"RESULT_VALUE" form:"RESULT_VALUE"`
	CREATE_DATE  sql.NullString `db:"CREATE_DATE" json:"CREATE_DATE" form:"CREATE_DATE"`
}

func (t *AptCmd) Project() {
	db, _ := initialize.GetYwkDB()

	myFunc := func(a any) {
		v, _ := a.(HealthCheckProject)
		resultValue, err := t.Decrypt(v.RESULT_VALUE.String)
		if err != nil {
			db.Exec(`UPDATE HEALTH_CHECK_PROJECT SET CHECK_NO = :1 WHERE ID = :2`, "1", v.ID)
			fmt.Printf("解密失败：%#v \t %#v \n", v.ID, err)
			return
		}

		updateSQL := fmt.Sprintf(`UPDATE HEALTH_CHECK_PROJECT SET  RESULT_VALUE = :1, CHECK_NO = :2 WHERE ID = :3`)
		ret, err := db.Exec(updateSQL, resultValue, "1", v.ID)
		if err != nil {
			fmt.Printf("修改失败：%#v \n", err)
			return
		}
		rows, _ := ret.RowsAffected()
		fmt.Printf("修改成功：%#v \t %#v \t %#v\n", v.ID, v.CREATE_DATE, rows)
	}

	task := &util.AsyncTask{ChanLen: 5000000, TaskNum: 2000}
	task.Start(myFunc)

	//id := "1950211742199922690"
	for i := 0; ; i++ {
		var results []HealthCheckProject

		sqlString := fmt.Sprintf(`SELECT ID, RESULT_VALUE, CREATE_DATE  FROM  HEALTH_CHECK_PROJECT WHERE (CHECK_NO = '2' OR CHECK_NO is null) ORDER BY  CREATE_DATE ASC OFFSET :1  ROWS FETCH NEXT 200000 ROWS ONLY`)

		err := db.Select(&results, sqlString, 0)
		fmt.Println("查询结束")
		if err != nil {
			fmt.Printf("查询列表错误：%#v \t %#v \n", sqlString, err)
			break
		}
		if results == nil {
			fmt.Printf("查询列表为空：%#v \t %#v \n", sqlString, err)
			break
		}

		for _, v := range results {
			task.Chan <- v
		}
		//id = results[len(results)-1].ID
	}

	task.Stop()
}

// Decrypt 解密
func (t *AptCmd) Sm4Test() {
	//a := "yqGRMkX6ejC1vl8eYvledQ=="
	db, _ := initialize.GetYwkDB()

	var list []HealthCheckProject
	err := db.Select(&list, "SELECT ID, CHECK_ID, RESULT_VALUE, CREATE_DATE FROM HEALTH_CHECK_PROJECT WHERE RESULT_VALUE  LIKE '%==%'")
	if err != nil {
		fmt.Printf("列表查询为空%v \n", err.Error())
		return
	}

	myFunc := func(a any) {
		v, _ := a.(HealthCheckProject)
		value, err := t.Decrypt(v.RESULT_VALUE.String)
		if err != nil {
			fmt.Printf("错误解码%v \n", v.RESULT_VALUE.String)
			return
		}
		_, err = db.Exec(`UPDATE HEALTH_CHECK_PROJECT SET RESULT_VALUE = :1 WHERE ID = :2`, value, v.ID)
		if err != nil {
			fmt.Printf("更新失败%v \n", err.Error())
			return
		}
		fmt.Printf("更新成功%v \t %v \n", v.ID, value)
	}

	task := &util.AsyncTask{ChanLen: 5000000, TaskNum: 2000}
	task.Start(myFunc)

	for _, v := range list {
		task.Chan <- v
	}
	task.Stop()
}

func (t *AptCmd) Decrypt(str string) (string, error) {
	key := []byte("5tgb6yhn7ujm8ik,")

	base, err := tool.Base64Decode(str)
	if err != nil {
		return "", err
	}
	decrypt, err := tool.SM4CBCDecrypt(key, key, base)
	if err != nil {
		return "", err
	}
	return string(decrypt), nil
}

func (t *AptCmd) BusinessDepartment() {
	db, _ := initialize.GetYwkDB()
	dbXtk, _ := initialize.GetXtkDB()

	//APPROVAL_USER_ID  BUSINESS_DEPARTMENT ID

	myFunc := func(a any) {
		v, _ := a.(Filing)
		fmt.Printf("正在处理：%#v \n", v.ID)

		var user SysUser
		sqlString2 := fmt.Sprintf(` SELECT ID, ENTERPRISE_ID, ENTERPRISE_NAME  FROM  SYS_USER WHERE ID = :1 OFFSET 0  ROWS FETCH NEXT 1 ROWS ONLY `)
		err := dbXtk.Get(&user, sqlString2, v.APPROVAL_USER_ID)
		if err != nil {
			fmt.Printf("账号查询错误：%#v \t %#v \n", v.ID, err)
			return
		}

		departmentArr := officeServiceApp.GetOfficeLevelName(user.ENTERPRISE_ID)
		if len(departmentArr) == 0 {
			return
		}
		var nameArr []string
		for _, v := range departmentArr {
			nameArr = append(nameArr, v.NAME.String)
		}
		department := strings.Join(nameArr, "-")

		ret, err := db.Exec("UPDATE JOB_FILING_RECORDS set BUSINESS_DEPARTMENT = :1  WHERE ID = :2", department, v.ID)
		if err != nil {
			fmt.Printf("修改失败：%#v \n", err)
			return
		}
		fmt.Printf("修改成功：%#v ====> %#v ====>  %#v\n", v.ID, department, ret)

	}

	task := &util.AsyncTask{ChanLen: 5500, TaskNum: 1000}
	task.Start(myFunc)

	n := 0
	for i := 0; ; i++ {
		var results []Filing

		sqlString := fmt.Sprintf(`SELECT ID, APPROVAL_USER_ID, BUSINESS_DEPARTMENT  
FROM  JOB_FILING_RECORDS 
WHERE BUSINESS_DEPARTMENT IS NULL AND APPROVAL_USER_ID IS NOT NULL
ORDER BY  CREATE_DATE  ASC OFFSET :1  ROWS FETCH NEXT 1000 ROWS ONLY`)

		err := db.Select(&results, sqlString, i*1000)
		if err != nil {
			fmt.Printf("错误：%#v \n", err)
			break
		}
		if results == nil {
			break
		}

		for _, v := range results {
			n++
			task.Chan <- v
			fmt.Printf("数量：%#v \n", n)
		}
	}

	task.Stop()
}
